package com.dwin.dingnuo.ui.detail;

import android.animation.ObjectAnimator;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.dwin.dingnuo.R;
import com.dwin.dingnuo.http.DwinConstants;
import com.dwin.dingnuo.http.MyRetrofit;
import com.dwin.dingnuo.http.beans.BackModel;
import com.dwin.dingnuo.http.request.DeviceLogAdd;
import com.dwin.dingnuo.http.request.ReqDeviceEdit;
import com.dwin.dingnuo.http.response.HomeDevice;
import com.dwin.dingnuo.http.response.RspDeviceDetail;
import com.dwin.dingnuo.mqtt.DataSynEvent;
import com.dwin.dingnuo.mqtt.MqttManager;
import com.dwin.dingnuo.ui.base.BaseActivity;
import com.dwin.dingnuo.ui.detail.tool.InstructTool;
import com.dwin.dingnuo.ui.detail.tool.JsonTool;
import com.dwin.dingnuo.utils.MobileUtil;
import com.dwin.dingnuo.utils.ToastUtil;
import com.dwin.dingnuo.views.DeviceWaitingDialog;
import com.dwin.dingnuo.views.DwinInputDialog;
import com.dwin.dingnuo.views.DwinRateDialog;
import com.dwin.dingnuo.views.DwinSmokeTimeDialog;
import com.dwin.dingnuo.views.NetLoadingDialog;
import com.google.gson.Gson;

import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import androidx.annotation.NonNull;
import okhttp3.RequestBody;
import retrofit2.Response;

/**
 * 设备详情页面
 * 远程操作：启动/停止 频率上升/下降 锁定（锁定状态本地开不了机）
 * 显示控制器工作状态:运行状态，停止状态，运行频率，电压，电流，功率，温度，用电量，运行时间
 * <p>
 * 账户分为多级：  一级：生产厂家：权限可分配到设备厂家/经销商/用户
 * 二级：设备厂家：权限可分配到设备厂家/经销商/用户
 * 三级：经销商：权限可分配到经销商/用户
 * 四级：用户
 * <p>
 * 4.1:账户权限：
 * 一级：生产厂家：查看/锁定设备厂家-经销商-用户
 * 二级：设备厂家：查看/锁定经销商及用户
 * 三级：经销商：查看/锁定用户
 * 四级：用户：查看/锁定/控制
 * 登录账户： 可查看管理名下所有设备
 * <p>
 * 123级用户，智能锁定设备。
 */
public class DeviceDetailActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "DeviceDetailActivity";
    // 设备详情
    private RspDeviceDetail.DeviceDetailInfo deviceDetail;
    private HomeDevice homeDevice; // 设备列表，传递的设备信息

    // 设备顶部参数：
    private TextView tv_header_title;
    TextView tv_header_right;
    private ImageView iv_lock, iv_fan; // 锁、电风扇
    private Animation mAnimation;
    private TextView tv_qzc_temp, tv_hzc_temp, tv_hyl_oxygen; // 前轴承，后轴承，含氧量
    private Button btn_detail_power_on, btn_detail_shutdown, btn_detail_reset; // 开机，关机，重启
    private Button btn_detail_paiyan;
    // 表格数据1
//    private TextView tv_rate_hz, tv_time_s;
//    private ImageView iv_rate_up, iv_rate_down;
    private TextView tv_set_rate, tv_detail_scpl;
    private TextView tv_set_smoke_rate,
        tv_set_smoke_time;
    //    private int frequency;
    private int set_frequency; // 设置频率
    private int set_smoke_frequency, set_smoke_time; // 设定的排烟时间（分钟），排烟频率

    private TextView tv_detail_sbbh, tv_detail_yxsj, tv_detail_jrdl, tv_detail_zdl;
    // 表格数据2
    private TextView tv_dbtx, tv_sbtz; // 设备状态显示
    private TextView tv_detail_srdy, tv_detail_scdy, tv_detail_scdl, tv_detail_scgl;
    private int is_locked = 0; // 当前是否锁定了。

    private static final int INTERACTIVE = 128;
    private static final int DELAY = 10 * 1000;
    private boolean isShowWaitingDialog = false;

    private String[] faultDesc;

    private Handler mHandlerInteractive = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.what == INTERACTIVE && isShowWaitingDialog) {
                isShowWaitingDialog = false;
                DeviceWaitingDialog.dismissprogress(); // 隐藏 hide
                ToastUtil.toastShort(mContext, R.string.failed_retry);
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_detail);
        EventBus.getDefault().register(this);

        faultDesc = getResources().getStringArray(R.array.fault_desc);
        homeDevice = (HomeDevice) getIntent().getSerializableExtra("device");
        initViews();
        if (homeDevice != null && homeDevice.devices_members_info != null) {
            getDeviceDetail(homeDevice.id);
        }
        updateUIByUserInfo();
    }

    private void updateUIByUserInfo() {
        if (mUser == null) return;
        if (mUser.role_id < 4) { // 123级用户，仅能锁定解锁设备。
            btn_detail_power_on.setEnabled(false);
            btn_detail_shutdown.setEnabled(false);
            btn_detail_reset.setEnabled(false);
            tv_set_rate.setEnabled(false);
            tv_header_right.setVisibility(View.GONE); // 123级用户，不能修改名称；4级可修改。
        }
    }


    @Subscribe
    public void onEvent(DataSynEvent message) {
        String desc = message.getDetail();
        // mqtt网络丢失，释放资源，重新建立连接
        Log.d(TAG, "onEvent mqtt lost" + desc);
        isNetLostFlag = true;
        reConnectMqtt();
    }

    //  通过EventBus，获取收到的mqtt消息
    @Subscribe
    public void onEvent(MqttMessage message) {
        String payLoad = new String(message.getPayload());
        Message tempMsg = mhandler.obtainMessage();
        tempMsg.obj = payLoad;
        mhandler.sendMessage(tempMsg);
    }

    Handler mhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            dismissMqttDialog();
            String message = (String) msg.obj;
            // 收到mqtt指令，更新页面UI。
            // Log.d(TAG, "handleMessage:" + message);
            onReceiveMqttMsg(message);
        }
    };

    public void onReceiveMqttMsg(String message) {
        if (isShowWaitingDialog) {
            mHandlerInteractive.removeMessages(INTERACTIVE);
            DeviceWaitingDialog.dismissprogress();
            isShowWaitingDialog = false;
        }
        Log.d(TAG, "onReceiveMqttMsg:" + message);
        try {
            JSONObject json = new JSONObject(message);
            if (json.has("input_voltage")) { // 输入电压
                int input_voltage = json.getInt("input_voltage");
                tv_detail_srdy.setText(input_voltage + "V");
            }
            if (json.has("output_voltage")) { // 输出电压
                int output_voltage = json.getInt("output_voltage");
                tv_detail_scdy.setText(output_voltage + "V");
            }
            if (json.has("output_current")) { // 输出电流
                int output_current = json.getInt("output_current");
                tv_detail_scdl.setText(output_current + "A");
            }
            if (json.has("output_power")) { // 输出功率
                int output_power = json.getInt("output_power");
                tv_detail_scgl.setText(output_power + "KW");
            }
            if (json.has("frequency")) { // 频率
                int frequency = json.getInt("frequency");
                tv_detail_scpl.setText(String.format("%.1f", frequency * 0.1) + " Hz");
            }
            if (json.has("set_frequency")) { // 频率
                set_frequency = json.getInt("set_frequency");
                tv_set_rate.setText(String.format("%.1f", set_frequency * 0.1) + " Hz");
            }
            // ------------- 处理排烟信息。start
            if (json.has("smoke_exhaust_time")) { // 排烟时间
                set_smoke_time = json.getInt("smoke_exhaust_time");
                tv_set_smoke_time.setText(String.format("%.1f", set_smoke_time * 1.0) + " min");
            }
            if (json.has("smoke_exhaust_frequency")) { // 排烟频率
                set_smoke_frequency = json.getInt("smoke_exhaust_frequency");
                tv_set_smoke_rate.setText(String.format("%.1f", set_smoke_frequency * 0.1) + " Hz");
            }
            // 排烟时间显示。smoke_exhaust_time_show
//            if (json.has("smoke_exhaust_time_show")) { // 排烟频率
//                int timeShow = json.getInt("smoke_exhaust_time_show");
//                if (timeShow > 0)
//                    btn_detail_paiyan.setText(String.format("排烟(%.1f min)", timeShow * 0.1f));
//            }
            // ------------- 处理排烟信息。end

            if (json.has("front_bearing_temperature")) { // 前轴温度
                int frontTemp = json.getInt("front_bearing_temperature");
                tv_qzc_temp.setText(String.valueOf(frontTemp));
            }
            if (json.has("back_bearing_temperature")) { // 后轴温度
                int backTemp = json.getInt("back_bearing_temperature");
                tv_hzc_temp.setText(String.valueOf(backTemp));
            }
            if (json.has("oxygen_content")) { // 含氧量
                int oxygen = json.getInt("oxygen_content");
                tv_hyl_oxygen.setText(String.valueOf(oxygen));
            }

            if (json.has("running_time")) {
                int running_time = json.getInt("running_time");
                tv_detail_yxsj.setText(running_time + "小时");
            }
            if (json.has("electricity_today")) {
                double electricity_today = json.getDouble("electricity_today");
//                tv_detail_jrdl.setText(String.format("%.2f", electricity_today * 0.01) + "度");
                tv_detail_jrdl.setText(electricity_today + " 度");
            }
            if (json.has("electricity_total")) {
                double electricity_total = json.getDouble("electricity_total");
                tv_detail_zdl.setText(electricity_total + " 度");
//                tv_detail_zdl.setText(String.format("%.2f", electricity_total * 0.01) + "度");
            }
            if (json.has("device_status")) { // 设备状态。
                String statusTxt = json.getString("device_status");
                if (TextUtils.isEmpty(statusTxt)) { // 内容为空
                    tv_sbtz.setVisibility(View.GONE);
                } else { // 内容非空
                    tv_sbtz.setText(statusTxt);
                    tv_sbtz.setVisibility(View.VISIBLE);
                }
            }
            if (json.has("fault_warning")) { // 故障预警
                int fault_warning = json.getInt("fault_warning");
                boolean[] faults = InstructTool.fault2BooleanArray(fault_warning);
                String showTxt = "";
                for (int i = 0; i < faults.length; i++) {
                    if (i != 11 && faults[i]) {
                        showTxt = faultDesc[i]; // 得到对应文本。
                        break;
                    }
                }
                if (!TextUtils.isEmpty(showTxt)) {
                    tv_dbtx.setText(showTxt);
                    tv_dbtx.setVisibility(View.VISIBLE);
                }
            }

            if (json.has("on_off")) {
                int on_off = json.getInt("on_off");
                iv_fan.clearAnimation();// 停止动画
                if (on_off == 1) {
                    iv_fan.startAnimation(mAnimation);
                }
            }
            if (json.has("is_locked")) {
                is_locked = json.getInt("is_locked");
                // 设备当前状态：is_locked（0解锁；1锁定）
                if (is_locked == 1) { // 设备锁定。点击给提属于
                 /*   btn_detail_power_on.setEnabled(false);
                    btn_detail_shutdown.setEnabled(false);
                    btn_detail_reset.setEnabled(false);
                    tv_set_rate.setEnabled(false);*/
//                    iv_lock.setTag(true);
//                    iv_lock.setImageResource(R.drawable.lock_locked);
                } else if (is_locked == 0) { // 解锁。
//                    iv_lock.setTag(false);
//                    iv_lock.setImageResource(R.drawable.lock_unlock);
                    if (mUser.role_id == 4) { // 4级用户，才可以操作按钮。
                        btn_detail_power_on.setEnabled(true);
                        btn_detail_shutdown.setEnabled(true);
                        btn_detail_reset.setEnabled(true);
                        tv_set_rate.setEnabled(true);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private boolean isNetLostFlag = false; // 网络切换，导致mqtt网络连接丢失。
    Handler mqttHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            reConnectMqtt();
        }
    };

    private void reConnectMqtt() {
        if (deviceDetail != null && isNetLostFlag) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    boolean b = MqttManager.reConnect();
                    if (b) {
                        MqttManager.getInstance().subscribe(); // 订阅消息
                        if (mqttHandler != null) {
                            mqttHandler.removeMessages(CODE_100);
                        }
                        Log.d(TAG, "mqtt reConnectMqtt 建立连接成功：" + b);
                    } else {
                        if (mqttHandler != null) {
                            mqttHandler.removeMessages(CODE_100);
                            mqttHandler.sendEmptyMessageDelayed(CODE_100, 10 * 1000);
                        }
                    }
                }
            }).start();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mqttHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                reConnectMqtt();
            }
        };
        if (deviceDetail != null && isNetLostFlag) {
            // 重新建立连接
            new Thread(new Runnable() {
                @Override
                public void run() {
                    boolean b = MqttManager.reConnect();
                    if (b) {
                        MqttManager.getInstance().subscribe(); // 订阅消息
                        if (mqttHandler != null) {
                            mqttHandler.removeMessages(100);
                        }
                        Log.d(TAG, "mqtt onResume 建立连接成功：" + b);
                    } else {
                        if (mqttHandler != null) {
                            mqttHandler.removeMessages(100);
                            mqttHandler.sendEmptyMessageDelayed(100, 10 * 1000);
                        }
                    }
                }
            }).start();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    MqttManager.getInstance().disConnect();
                    MqttManager.getInstance().release();
                    mqttHandler.removeMessages(CODE_100);
                    mqttHandler = null;
                } catch (MqttException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    @Override
    protected void initViews() {
        ImageButton btn_header_left = findView(R.id.btn_header_left);
        btn_header_left.setOnClickListener(this);
        tv_header_title = findViewById(R.id.tv_header_title);
//        tv_header_title.setText("设备:" + homeDevice.device_num);
        tv_header_title.setText("设备详情页面");

        tv_header_right = findViewById(R.id.tv_header_right);
        tv_header_right.setVisibility(View.VISIBLE);
        tv_header_right.setText("修改名称");
        tv_header_right.setOnClickListener(this);

        // 上部分数据
        iv_lock = findViewById(R.id.iv_lock);// 锁、电风扇
        iv_lock.setOnClickListener(this);
        iv_fan = findViewById(R.id.iv_fan);
        mAnimation = AnimationUtils.loadAnimation(this, R.anim.rotaterepeat);
        mAnimation.setInterpolator(new LinearInterpolator());
        mAnimation.setRepeatCount(ObjectAnimator.INFINITE);
        mAnimation.setFillAfter(true);
        mAnimation.setRepeatMode(Animation.RESTART);

        tv_qzc_temp = findViewById(R.id.tv_qzc_temp);  // 前轴承，后轴承，含氧量
        tv_hzc_temp = findViewById(R.id.tv_hzc_temp);
        tv_hyl_oxygen = findViewById(R.id.tv_hyl_oxygen);

        btn_detail_power_on = findViewById(R.id.btn_detail_power_on); // 开机，关机，重启
        btn_detail_shutdown = findViewById(R.id.btn_detail_shutdown);
        btn_detail_reset = findViewById(R.id.btn_detail_reset);
        btn_detail_power_on.setOnClickListener(this);
        btn_detail_shutdown.setOnClickListener(this);
        btn_detail_reset.setOnClickListener(this);
        btn_detail_paiyan = findViewById(R.id.btn_detail_paiyan);
        btn_detail_paiyan.setOnClickListener(this);

        // 中部分UI
//        tv_rate_hz = findViewById(R.id.tv_rate_hz);
//        tv_time_s = findViewById(R.id.tv_time_s);
//        iv_rate_up = findViewById(R.id.iv_rate_up);
//        iv_rate_down = findViewById(R.id.iv_rate_down);
//        iv_rate_down.setOnClickListener(this);
//        iv_rate_up.setOnClickListener(this);
        tv_set_smoke_rate = findViewById(R.id.tv_set_smoke_rate);
        tv_set_smoke_time = findViewById(R.id.tv_set_smoke_time);
        tv_set_smoke_rate.setOnClickListener(this);
        tv_set_smoke_time.setOnClickListener(this);

        tv_set_rate = findView(R.id.tv_set_rate);
        tv_set_rate.setOnClickListener(this);
        tv_detail_scpl = findView(R.id.tv_detail_scpl);

        tv_detail_sbbh = findViewById(R.id.tv_detail_sbbh);
        tv_detail_yxsj = findViewById(R.id.tv_detail_yxsj);
        tv_detail_jrdl = findViewById(R.id.tv_detail_jrdl);
        tv_detail_zdl = findViewById(R.id.tv_detail_zdl);
        if (homeDevice != null && homeDevice.device_num != null)
            tv_detail_sbbh.setText(homeDevice.device_num); // 显示设备编号。

        // 下部分UI
        tv_dbtx = findViewById(R.id.tv_dbtx); // 电表通讯、设备停止
        tv_sbtz = findViewById(R.id.tv_sbtz);
        tv_detail_srdy = findViewById(R.id.tv_detail_srdy);
        tv_detail_scdy = findViewById(R.id.tv_detail_scdy);
        tv_detail_scdl = findViewById(R.id.tv_detail_scdl);
        tv_detail_scgl = findViewById(R.id.tv_detail_scgl);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_header_left:
                onBackPressed();
                break;
            case R.id.tv_header_right: // 修改名称
                String originalName = homeDevice.devices_members_info.name; // device.devices_members_info.name
                final DwinInputDialog dialog = new DwinInputDialog(mContext, R.style.DialogTheme)
                        .setMyTitle(getResources().getString(R.string.modify_device_name))
                        .setMyName(originalName)
                        .setMyNameHint(getResources().getString(R.string.input_device_name));
                dialog.setDialogListener(new DwinInputDialog.MyDialogListener() {
                    @Override
                    public void onClickPositive(String name) {
                        dialog.dismiss();
                        postDeviceEdit(name); // 修改设备名称
                    }

                    @Override
                    public void onCLickNegative() {
                        dialog.dismiss();
                    }
                });
                dialog.show();
                break;

            case R.id.tv_header_title: // 模拟发送mqtt写指令。
                Map map = new HashMap();
                map.put(InstructTool.type_CMD, InstructTool.typeW);
                map.put("mainmotor_start", 1);
                sendMqttMsg(map);
                break;

            case R.id.iv_lock: // 锁定，解锁
                if (iv_lock.getTag() == null) {
                    iv_lock.setTag(false);
                }
                boolean isLocked = (boolean) iv_lock.getTag();
                isLocked = !isLocked;
                iv_lock.setTag(isLocked);
                if (isLocked) {
                    iv_lock.setImageResource(R.drawable.lock_locked);
                    buildOperateMsg(32); // 锁屏
                } else {
                    buildOperateMsg(33); // 解锁。
                    iv_lock.setImageResource(R.drawable.lock_unlock);
                }
                break;

            case R.id.btn_detail_power_on:  // 开机 0x12
                if (is_locked == 1) {
                    ToastUtil.toastLong(mContext, R.string.device_locked);
                    return;
                }
                buildOperateMsg(18);
                break;
            case R.id.btn_detail_shutdown:  // 停机 0x13
                if (is_locked == 1) {
                    ToastUtil.toastLong(mContext, R.string.device_locked);
                    return;
                }
                buildOperateMsg(19);
                break;
            case R.id.btn_detail_reset:  // 复位 0x11
                if (is_locked == 1) {
                    ToastUtil.toastLong(mContext, R.string.device_locked);
                    return;
                }
                buildOperateMsg(17);
                break;
            case R.id.btn_detail_paiyan: // 一键排烟
                if (is_locked == 1) {
                    ToastUtil.toastLong(mContext, R.string.device_locked);
                    return;
                }
                buildOperateMsg(20); // 设备进行排烟。
                break;

            case R.id.tv_set_rate: // 设置频率。
                if (is_locked == 1) {
                    ToastUtil.toastLong(mContext, R.string.device_locked);
                    return;
                }
                setRateDialog(set_frequency * 0.1);
                break;

            case R.id.tv_set_smoke_rate: // 设置排烟频率
                if (is_locked == 1) {
                    ToastUtil.toastLong(mContext, R.string.device_locked);
                    return;
                }
                setSmokeRateDialog(set_smoke_frequency * 0.1);
                break;
            case R.id.tv_set_smoke_time: // 设置排烟时间，分钟。 TODO
                if (is_locked == 1) {
                    ToastUtil.toastLong(mContext, R.string.device_locked);
                    return;
                }
                setSmokeTimeDialog(set_smoke_time * 1.0f);
                break;
            default:
                break;
        }
    }

    // 设置排烟时间。
    private void setSmokeTimeDialog(double time) {
        String originalName = String.valueOf(time);
        final DwinSmokeTimeDialog dialog = new DwinSmokeTimeDialog(mContext, R.style.DialogTheme)
                .setMyTitle(getResources().getString(R.string.input_smoke_time))
                .setMyName(originalName) // 原始的值。
                .setMyNameHint(getResources().getString(R.string.input_smoke_time_name));
        dialog.setDialogListener(new DwinSmokeTimeDialog.MyDialogListener() {
            @Override
            public void onClickPositive(String rate) {
                dialog.dismiss();
                Map map = new HashMap();
                try {
                    float smokeTimeSet = Float.parseFloat(rate);
                    if (smokeTimeSet > 999) {
                        smokeTimeSet = 999;
                    } else if (smokeTimeSet < 0) {
                        smokeTimeSet = 0;
                    }
                    map.put("smoke_exhaust_time", (int) (smokeTimeSet)); // 排烟时间，直接传递。
                    tv_set_smoke_time.setText(smokeTimeSet + " min");
                    buildMqttMsg(map);
                } catch (Exception e) {
                    ToastUtil.toastLong(mContext, "输入正常排烟时间");
                }
            }

            @Override
            public void onCLickNegative() {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

//    设置排烟频率。
    private void setSmokeRateDialog(double rate) {
        String originalName = String.valueOf(rate);
        final DwinRateDialog dialog = new DwinRateDialog(mContext, R.style.DialogTheme)
                .setMyTitle(getResources().getString(R.string.modify_smoke_rate_name))
                .setMyName(originalName) // 原始的值。
                .setMyNameHint(getResources().getString(R.string.input_smoke_rate_name));
        dialog.setDialogListener(new DwinRateDialog.MyDialogListener() {
            @Override
            public void onClickPositive(String rate) {
                dialog.dismiss();
                Map map = new HashMap();
                try {
                    float rateSet = Float.parseFloat(rate);
                    if (rateSet > 200) {
                        rateSet = 200;
                    } else if (rateSet < 0) {
                        rateSet = 0;
                    }
                    map.put("smoke_exhaust_frequency", (int) (rateSet * 10)); // 频率传值，*10再传给设备。
                    tv_set_smoke_rate.setText(rateSet + " Hz");
                    buildMqttMsg(map);
                } catch (Exception e) {
                    ToastUtil.toastLong(mContext, "输入正常的排烟频率");
                }
            }

            @Override
            public void onCLickNegative() {
                dialog.dismiss();
            }
        });
        dialog.show();
    }


    private void setRateDialog(double rate) {
        String originalName = String.valueOf(rate);
        final DwinRateDialog dialog = new DwinRateDialog(mContext, R.style.DialogTheme)
                .setMyTitle(getResources().getString(R.string.modify_rate_name))
                .setMyName(originalName) // 原始的值。
                .setMyNameHint(getResources().getString(R.string.input_rate_name));
        dialog.setDialogListener(new DwinRateDialog.MyDialogListener() {
            @Override
            public void onClickPositive(String rate) {
                dialog.dismiss();
                Map map = new HashMap();
                try {
                    float rateSet = Float.parseFloat(rate);
                    if (rateSet > 200) {
                        rateSet = 200;
                    } else if (rateSet < 0) {
                        rateSet = 0;
                    }
                    map.put("set_frequency", (int) (rateSet * 10)); // 频率传值，*10再传给设备。
                    tv_set_rate.setText(rateSet + " Hz");
                    buildMqttMsg(map);
                } catch (Exception e) {
                    ToastUtil.toastLong(mContext, "输入正常的频率");
                }
            }
            @Override
            public void onCLickNegative() {
                dialog.dismiss();
            }
        });
        dialog.show();
    }


    // 得到设备详情
    private void getDeviceDetail(int device_id) { // devices.get(position).id
        if (!isNetworkConnected(mContext)) {
            ToastUtil.toastShort(mContext, R.string.net_error);
            return;
        }
        NetLoadingDialog.showprogress(mContext, true);
        Map<String, String> map = new HashMap<>();
        map.put("device_id", "" + device_id);
        map.put("websocket", "0"); // 0普通mqtt帐号 1websocket mqtt帐号 （不携带默认为1）
        MyRetrofit.getInstance().getDeviceDetail(mUser.auth, language, map, new retrofit2.Callback<RspDeviceDetail>() {
            @Override
            public void onResponse(retrofit2.Call<RspDeviceDetail> call, Response<RspDeviceDetail> response) {
                NetLoadingDialog.dismissprogress();
                if (DwinConstants.HTTP_OK == response.body().code) {
                    // 成功，更新UI
                    deviceDetail = response.body().data;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            String mqttUrl = "tcp://" + deviceDetail.mqtt_info.mqtt_server
                                    + ":" + deviceDetail.mqtt_info.mqtt_port;
                            String deviceUniId = MobileUtil.getUniqueId4Mqtt(mContext);
                            MqttManager.release(); // 避免出现占用连接，导致不能重连mqtt服务器的问题。
                            boolean b = MqttManager.getInstance().creatConnect(mqttUrl, deviceDetail.mqtt_info.mqtt_user, deviceDetail.mqtt_info.mqtt_pw,
                                    replaceLast(deviceDetail.user_topic, "cli", "json"),
                                    replaceLast(deviceDetail.user_send_topic, "cli", "json"), deviceUniId);
                            Log.d(TAG, "mqtt 建立连接成功：" + b);
                            MqttManager.getInstance().subscribe(); // 订阅消息

                            buildRAMReadMsg(); // 查询内存指令发送
                        }
                    }).start();
                } else if (DwinConstants.HTTP_TOKEN_100002 == response.body().code) {
                    userLogout();
                } else {
                    ToastUtil.toastShort(mContext, response.body().message);
                }
            }

            @Override
            public void onFailure(retrofit2.Call<RspDeviceDetail> call, Throwable t) {
                NetLoadingDialog.dismissprogress();
            }
        });
    }


    private void buildMqttMsg(Map map) {
        map.put(InstructTool.type_CMD, InstructTool.typeW);
        sendMqttMsg(map);
    }

    private void buildOperateMsg(int value) {
        Map map = new HashMap();
        map.put(InstructTool.type_CMD, InstructTool.typeW);
        map.put("device_operation", value); // 堵料传感器标定
        sendMqttMsg(map);
    }

    // 生成读取内存指令，并发送
    private void buildRAMReadMsg() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mHandlerInteractive.removeMessages(INTERACTIVE);
                mHandlerInteractive.sendEmptyMessageDelayed(INTERACTIVE, DELAY);
                isShowWaitingDialog = true;
                DeviceWaitingDialog.showprogress(mContext, false);

                final String message = new JSONObject(InstructTool.deviceQuery()).toString();
                Log.d(TAG, "send query hex value: " + message);
                MqttManager.getInstance().publish(message.getBytes());

                final String message2 = new JSONObject(InstructTool.deviceQuery2()).toString();
                Log.d(TAG, "send query hex value: " + message2);
                MqttManager.getInstance().publish(message2.getBytes());

                final String message3 = new JSONObject(InstructTool.deviceQuery3()).toString();
                Log.d(TAG, "send query hex value: " + message3);
                MqttManager.getInstance().publish(message3.getBytes());
            }
        });
    }

    public void sendMqttMsg(Map map) {
        mHandlerInteractive.removeMessages(INTERACTIVE);
        mHandlerInteractive.sendEmptyMessageDelayed(INTERACTIVE, DELAY);
        isShowWaitingDialog = true;
        DeviceWaitingDialog.showprogress(mContext, false);

        final String message = new JSONObject(map).toString();
        if (map.containsKey(JsonTool.type_CMD)) {
            String value = (String) map.get(JsonTool.type_CMD);
            if (JsonTool.typeW.equals(value)) { // 写操作指令；
                map.remove(JsonTool.type_CMD); // 删除__command_type
                addDeviceLogs(map);
            }
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "send hex value: " + message);
                MqttManager.getInstance().publish(message.getBytes());
            }
        }).start();
    }

    // 保存设备操作日志 1217
    public void addDeviceLogs(final Map map) {
        if (mUser == null || mUser.auth.isEmpty()) {
            return;
        }
        DeviceLogAdd info = new DeviceLogAdd(String.valueOf(homeDevice.id), map);
        Gson gson = new Gson();
        String obj = gson.toJson(info);
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), obj);
        MyRetrofit.getInstance().addLogs(mUser.auth, language, body, new retrofit2.Callback<BackModel>() {
            @Override
            public void onResponse(retrofit2.Call<BackModel> call, Response<BackModel> response) {
                if (DwinConstants.HTTP_OK == response.body().code) {
                    Log.d(TAG, "log success:" + map.toString());
                } else if (DwinConstants.HTTP_TOKEN_100002 == response.body().code) {
                } else {
                    Log.d(TAG, "log failed:" + map.toString());
                }
            }

            @Override
            public void onFailure(retrofit2.Call<BackModel> call, Throwable t) {
                Log.d(TAG, "onFailure: ");
            }
        });
    }


    // 修改设备名称
    private void postDeviceEdit(final String deviceName) {
        if (!isNetworkConnected(mContext)) {
            ToastUtil.toastShort(mContext, R.string.net_error);
            return;
        }
        NetLoadingDialog.showprogress(mContext, true);
        ReqDeviceEdit info = new ReqDeviceEdit();
        info.device_id = homeDevice.id;
        info.name = deviceName;
        String obj = new Gson().toJson(info);
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), obj);

        MyRetrofit.getInstance().deviceEdit(mUser.auth, language, body, new retrofit2.Callback<BackModel>() {
            @Override
            public void onResponse(retrofit2.Call<BackModel> call, Response<BackModel> response) {
                if (DwinConstants.HTTP_OK == response.body().code) {
                    homeDevice.devices_members_info.name = deviceName;
                    ToastUtil.toastShort(mContext, "名称修改成功");
                } else if (DwinConstants.HTTP_TOKEN_100002 == response.body().code) {
                    userLogout();
                } else {
                    ToastUtil.toastShort(mContext, response.body().message);
                }
                NetLoadingDialog.dismissprogress();
            }

            @Override
            public void onFailure(retrofit2.Call<BackModel> call, Throwable t) {
                NetLoadingDialog.dismissprogress();
            }
        });
    }

}
